package com.summer.ChengXuYuanMianShiJingDian;

import java.util.HashSet;
import java.util.Set;

public class Q1_6 {
    public String compressString(String S) {
        if (S.length()==0) return S;
        else {
            Set<Character> set = new HashSet<>();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(S.charAt(0));
            set.add(S.charAt(0));
            int count = 1;
            for (int i = 1;i<S.length();i++){
                int fs = set.size();
                set.add(S.charAt(i));
                int ss = set.size();

                if (fs==ss){
                    count++;
                }else {
                    set.remove(S.charAt(i-1));
                    stringBuilder.append(count).append(S.charAt(i));
                    count =1;
                }
            }
            int len = stringBuilder.append(count).length();
            if (len>=S.length())return S;
            else return stringBuilder.toString();
        }

    }
}
